﻿using Abp.AspNetCore.Mvc.Controllers;
using Abp.Domain.Repositories;
using Batman.Core;
using Batman.Jianbei.Forum.Core.ChatRoom;
using Batman.Jianbei.Forum.Core.Consts;
using Batman.Jianbei.Forum.Repositories.Mongo;
using Batman.Jianbei.Forum.SignalR;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.SignalR;
using System.Linq;
using System.Threading.Tasks;

namespace Batman.Jianbei.Forum.Areas.ChatRoom
{
    [Area(RouteNames.ChatRoom)]
    [Authorize]
    public class HubController : AbpController
    {
        public IHubContext<ChatHub> _hubContext { get; set; }

        public MongoRepositoryBase<TextHis> _textHisCollection { get; set; }

        public IRepository<Mask, string> _maskRepo { get; set; }

        /// <summary>
        /// 发送文本消息
        /// </summary>
        /// <param name="roomId"></param>
        /// <param name="text"></param>
        /// <returns></returns>
        public async Task<IActionResult> SendText(string roomId, string text, string maskId, string msgId)
        {
            var uid = User.GetWxUserId();
            var mask = _maskRepo.GetQuery().FirstOrDefault(t => t.Id == maskId);

            _textHisCollection.Insert(new TextHis(uid, roomId, mask, text));
            var method = $"{roomId}_text"; // 以房间ID+_text作为方法
            // 参数1：房间号 参数2：消息文本  参数3：发送者 参数4：消息类型
            await _hubContext.Clients.All.SendAsync(method, text, roomId, maskId, msgId, "text");
            return this.Ok();
        }

        /// <summary>
        /// 退出房间
        /// </summary>
        /// <param name="roomId"></param>
        /// <param name="maskId"></param>
        /// <param name="msgId"></param>
        /// <returns></returns>
        public async Task<IActionResult> Quit(string roomId, string maskId, string msgId)
        {
            var method = $"{roomId}_quit"; // 以房间ID+_text作为方法
            // 参数1：房间号 参数2：消息文本  参数3：发送者
            await _hubContext.Clients.All.SendAsync(method, roomId, maskId, msgId);
            return this.Ok();
        }

    }
}
